clear all;
clc;

load mnist_train;
load mnist_test;
load 7nng;
c = 10;
C = 1;
l = size(yL,2);
n = size(A,1);
Y = yL';

sz = zeros(c,1);
idx = cell(10,1);
for i = 1:c
    idx{i}=find(Y==(i-1));
    sz(i)=size(idx{i},1);
end

ix = cell(c,c);
yl = cell(c,c);
Y = cell(c,c);
sx = cell(c,c);

for i = 1:c
    for j = i+1:c
        ix{i,j} = [idx{i};idx{j}];
        sx{i,j} = sz(i)+sz(j);
        yl{i,j} = [ones(sz(i),1);-ones(sz(j),1)];
        Y{i,j} = sparse(ix{i,j},1:sx{i,j},yl{i,j},n,sx{i,j});
    end
end

disp('Start optimization...');
tic

alp = cell(c,c);

for i = 1:c
    for j = i+1:c
        tic
        T = Y{i,j}'*A*Y{i,j};
        alp{i,j} = quadprog(T,-ones(sx{i,j},1),[],[],[],[],zeros(sx{i,j},1),C*ones(sx{i,j},1));
        %alp{i,j} = zeros(sx{i,j},1);
        toc
    end
end

vot = zeros(n,c);

for i = 1:c
    for j = i+1:c
        chip = A*sparse(ix{i,j},1,alp{i,j},n,1);
        %vot(:,i) = vot(:,i)+(chip > 0).*chip;
        %vot(:,j) = vot(:,j)-(chip < 0).*chip;
        vot(:,i) = vot(:,i)+(chip > 0);
        vot(:,j) = vot(:,j)+(chip < 0);
    end
end

[~,Yp] = max(vot,[],2);
Yp = Yp-1;

trerr = calerr(Yp(1:l),yL')
tserr = calerr(Yp(l+1:n),yU')
